---------------------------------------------------------------
-- @Description：         robot_logic
---------------------------------------------------------------
local skynet = require "skynet"
local CMD = require "game_cmds"
local log = require "sky_log"
local packetbase = require "lua_packetbase"
local socket = require "skynet.socket"
local uu = require "sky_utils"
local gg = require "game_utils"
local cc = require "sky_call"
local game_actions = require "game_actions"
require "def"

local M = {
    --GAME_TYPE必须写，上层需要调用
    GAME_TYPE = {
        TABLE_TYPE.TARNEEB,
    },
    --定时器运行count计数
    TIME_COUNT = 0,
    --最大人数  
    MAX_PLAYER = 4,
}

--塔尼布牌局桌子状态
local GAME_STATE = {
    GAME_TARNEEB_STATE_FREE             =   0, --空闲阶段
    GAME_TARNEEB_STATE_READY            =   1, --准备阶段
    GAME_TARNEEB_STATE_CALL_GOALS       =   2, --叫分
    GAME_TARNEEB_STATE_CHIOCE_COLOR     =   3, --定花色
    GAME_TARNEEB_STATE_DEARL_CARD       =   4, --出牌
    GAME_TARNEEB_STATE_ROUND_OVER       =   5, --一轮结束
    GAME_TARNEEB_STATE_ROUND_OVERTIMER  =   6, --定时开始游戏状态
    GAME_TARNEEB_STATE_GAME_OVER        =   7, --游戏结束状态
}
--============================= Local Function =============================--
local function send_msg(fd, msg, size)
    socket.write(fd, msg, size)
end

local function on_login_success(robot, fd, packet)
    local table_info = {}
    table_info.game_state = packet:read_byte()
    table_info.dealer_seatid = packet:read_byte()
    table_info.current_bount = packet:read_int()     --回合
    table_info.current_round = packet:read_int()     --轮
    table_info.current_sit_player_count = packet:read_byte() --当前坐下玩家数量
    table_info.current_ju = packet:read_int()

    table_info.first_outcard_seatid = packet:read_byte()
    table_info.current_outcard_seatid = packet:read_byte()
    table_info.team_1_score = packet:read_int()
    table_info.team_2_score = packet:read_int()
    table_info.call_score_seatid = packet:read_byte()
    table_info.call_score = packet:read_byte()
    table_info.main_color = packet:read_byte()
    table_info.blind = packet:read_int64()       --桌子底注
    table_info.players = {}
    table_info.game_detail = {}

    --玩家基本信息
    local already_sit_t = {}
    for i=1, table_info.current_sit_player_count do
        local player_detail_t = {}
        player_detail_t.seat_id = tonumber(packet:read_byte())
        player_detail_t.user_id = packet:read_int64()
        player_detail_t.state  = tonumber(packet:read_byte())
        player_detail_t.mandateFlag = tonumber(packet:read_byte())      --是否被托管 (true托管)
        player_detail_t.level = packet:read_int()
        player_detail_t.player_base_info = packet:read_string()  --用户基本信息
        player_detail_t.chips = packet:read_int64()   --玩家筹码
        player_detail_t.is_real_player = packet:read_int()   --是否真人

        table_info.players[tonumber(player_detail_t.seat_id)] = player_detail_t
        table.insert(already_sit_t, player_detail_t.seat_id)
    end

    --玩家叫分出牌信息
    for i=1, table_info.current_sit_player_count do
        local table_game_t = {}
        table_game_t = {}
        table_game_t.seat_id = tonumber(packet:read_byte())
        table_game_t.goals = tonumber(packet:read_byte())  --服务器上固定写0 [无用信息]
        --叫分阶段
        if table_info.game_state==2 then
            table_game_t.is_fold = tonumber(packet:read_byte())
            table_game_t.call_score = packet:read_int()
        elseif table_info.game_state==4 then
            table_game_t.card_num= packet:read_short()
        end
        table_info.game_detail[tonumber(table_game_t.seat_id)] = table_game_t
    end
    table_info.robot_num = tonumber(packet:read_byte())

    local sit_pos = uu.boyaa_get_seatid(M.MAX_PLAYER, already_sit_t, TABLE_TYPE.TARNEEB)
    log.warning("on_login_success robot get sit_pos: ",  " user_id="..(robot.db_info.id or "nil").." sit_pos="..(sit_pos or "nil") 
       .." platid="..(robot.platid or "nil").." svid="..(robot.config_info.svid or "nil").." tid="..(robot.config_info.tid or "nil") )
    
    if sit_pos then
        --log.info("send sitdown msg!", "robot_id="..(robot.db_info.id or "nil").." sit_pos="..sit_pos)
        robot.game_info = {}
        robot.game_info.user_id = tonumber(robot.db_info.id)
        robot.game_info.platid = tonumber(robot.config_info.platid)
        robot.game_info.svid = tonumber(robot.config_info.svid)
        robot.game_info.tid = tonumber(robot.config_info.tid)
        robot.game_info.table_type = tonumber(robot.config_info.table_type)
        robot.game_info.followuid = tonumber(robot.followuid)
        robot.game_info.sit_pos = sit_pos
        robot.game_info.table_info = table_info

        local pack = packetbase.create_writebase()
        pack:write_begin(CMD.CLIENT_COMMAND_TARNEEB_SIT_REQUEST)
        pack:write_byte(sit_pos)
        pack:write_end()
    
        local msg, size = pack:return_buf()
        send_msg(fd, msg, size)
    else
        log.error("robot on_player_sitdown user_id=", (robot.db_info.id or "nil").." sit_pos="..(sit_pos or "nil")
            .." platid="..(robot.platid or "nil").." svid="..(robot.config_info.svid or "nil").." tid="..(robot.config_info.tid or "nil") )
    
        skynet.send(skynet.self(), "lua", "disconnect_server")
    end
end

local function on_sit_success(robot, fd, packet)
    local robot_info = {}
    robot_info.seat_id = packet:read_byte()
    robot_info.user_name = packet:read_string()
    robot_info.level = packet:read_int() 
    robot_info.chips = packet:read_int64()
    robot_info.level = packet:read_int()
    robot_info.new_level = packet:read_int()
    robot_info.small_level = packet:read_int()
    robot_info.stars = packet:read_int()
    robot_info.is_robot = 1
    robot_info.is_real_player = 0
    robot_info.user_id = robot.user_id

    robot.m_seatid = tonumber(robot_info.seat_id)
    robot.table_info.players[robot.m_seatid] = robot_info

    game_actions.init(robot)
end

local function on_broadcast_user_sit(robot, fd, packet)
    if not robot.sit_pos then 
        return
    end

    local play_info = {}

    play_info.seat_id = packet:read_byte()
    play_info.user_id = packet:read_int64()
    play_info.level = packet:read_int()
    play_info.user_name = packet:read_string()
    play_info.icon = packet:read_string()
    play_info.is_real_player = packet:read_byte()
    play_info.chips = packet:read_int64()
    play_info.new_level = packet:read_int()
    play_info.small_level = packet:read_int()
    play_info.stars = packet:read_int()

    robot.table_info.players[tonumber(play_info.seat_id)] = play_info
end

--============================= MSG =============================--
--定时器德州和塔尼布机器人暂时都没有用到，所以先在上层屏蔽了，
--后续需要时再开启，这里先留着接口
function M.do_timer()
    M.TIME_COUNT = M.TIME_COUNT + 1
    log.info("robot_logic (agent)[ "..skynet.self().." ] do_timer! count=",M.TIME_COUNT)
end

function M.login_game(robot, fd)
    local pack = packetbase.create_writebase()
    pack:write_begin(CMD.CLIENT_COMMAND_TARNEEB_LOGIN)
    pack:write_int(tonumber(robot.config_info.tid))   
    pack:write_int64(tonumber(robot.db_info.id))
    pack:write_string(LOGIN_INFO.mtkey)
    pack:write_end()

    local msg, size = pack:return_buf()
    send_msg(fd, msg, size)

    return size
end

function M.logout_game(robot, fd)
    --机器人金额超最大金额时，金钱减半
    local robot_money_limit = tonumber(skynet.getenv("robot_money_limit"))
    if robot_money_limit then
        local money = cc.call_memdb("get_money", robot.platid, tonumber(robot.db_info.id))
        if money and (money >= robot_money_limit) then
            local delta_money = -(money/2)
            cc.call_memdb("update_money", tonumber(robot.platid), tonumber(robot.db_info.id), tonumber(delta_money))

            log.info("robot logout_game update_money: ", "robot_id="..robot.db_info.id.." before_money="..money)
            local after_money = cc.call_memdb("get_money", robot.platid, tonumber(robot.db_info.id))
            log.info("robot logout_game update_money: ", "robot_id="..robot.db_info.id.." after_money="..after_money)
        end
    end

    local write_pack = packetbase.create_writebase()
    write_pack:write_begin(CMD.CLIENT_COMMAND_TARNEEB_LOGOUT)
    write_pack:write_int(tonumber(robot.config_info.tid))
    write_pack:write_int64(tonumber(robot.db_info.id))
    write_pack:write_string(3)
    write_pack:write_end()

    local msg, size = write_pack:return_buf()
    send_msg(fd, msg, size)
end

M.actions = {
    [CMD.SERVER_COMMAND_TARNEEB_LOGIN_SUCCESS] = on_login_success,
    [CMD.SERVER_COMMAND_TARNEEB_SIT_SUCCESS] = on_sit_success,
    [CMD.SERVER_BROADCAST_TARNEEB_USER_SIT] = on_broadcast_user_sit,
    

}
setmetatable(M.actions, {__index=game_actions.actions})

return M